﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Model;
using Dal;
using easysql;
namespace Web.service.system
{
    /// <summary>
    /// ResourceService 的摘要说明
    /// </summary>
    public class ResourceService : BaseService<ResourceModel>
    {

        private ResourceDal dal = DalFactory.CreateResourceDal();

        //上传单个文件
        public object upload(HttpContext context)
        {
            HttpFileCollection files = context.Request.Files;
            if (files.Count > 0)
            {
                string guid = System.Guid.NewGuid().ToString();
                string filePath = AppDomain.CurrentDomain.BaseDirectory + "/resource/" + guid + ".resource";
                files[0].SaveAs(filePath);

                ResourceModel rm = new ResourceModel();
                rm.path = filePath;
                rm.size = files[0].ContentLength;
                rm.filename = files[0].FileName;
                rm.createTime = DateTime.Now;
                rm.guid = Guid.NewGuid().ToString();
                dal.Add_AutoSetId(rm);
                rm.path = null;
                return rm;
            }
            throw new IException("上传文件失败");
        }

        public void download(HttpContext context)
        {
            String guid = context.Request["guid"];


            ResourceModel model = dal.queryByGuid(guid);

            context.Response.Clear();
            context.Response.Charset = "UTF-8";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.ContentType = "application/x-zip-compressed";
            // Http 协议中有专门的指令来告知浏览器, 本次响应的是一个需要下载的文件. 格式如下:
            // Content-Disposition: attachment;filename=filename.txt
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + model.filename);
            context.Response.TransmitFile(model.path, 0, model.size);
            context.Response.End();
        }

    }
}